package
{
    import com.bit101.components.ComboBox;
    import com.bit101.components.Label;
    import com.bit101.components.List;
    import com.bit101.components.PushButton;
    import com.bit101.components.RadioButton;
    import com.bit101.components.Text;
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.events.MouseEvent;
    import flash.events.TextEvent;
    import flash.events.TimerEvent;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.text.StyleSheet;
    import flash.text.TextField;
    import flash.text.TextFieldType;
    import flash.text.TextFormat;
    import flash.ui.Keyboard;
    import flash.utils.Timer;
    import mge.Localization;
    import mge.ui.ModalDialog;
    import mge.ui.TextTyped;
    
	/**
	 * ...
	 * @author ivan
	 */
	public class LocEditor extends Sprite 
	{
    private var loc:Localization;
    
    [Embed(source='../res/baloon.swf', symbol='I_Balloon')]
    public static const rBalloon:Class;
        
		public function LocEditor():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
    
    private function init(e:Event = null):void
    {
      removeEventListener(Event.ADDED_TO_STAGE, init);
      loadStyle();
    }
    
    private function loadStyle(e:Event = null):void
    {
      var request:URLRequest = new URLRequest("style.css");
      
      loader = new URLLoader();
      loader.addEventListener(Event.COMPLETE, onStyleLoaded);
      loader.load(request);
    }
    
    private function onStyleLoaded(e:Event):void
    {
      style = new StyleSheet();
      style.parseCSS(loader.data);
      
      createEditor();
    }
    
    private var loader:URLLoader;
        
		private function createEditor():void 
		{
      // Setup stage
      stage.scaleMode = StageScaleMode.NO_SCALE;
      stage.align = StageAlign.TOP_LEFT;
      stage.tabChildren = false;
      stage.stageFocusRect = false;
      
      // Draw a background
      var sprite:Sprite = new Sprite();
        sprite.graphics.beginFill(0xAAAAAA);
        sprite.graphics.drawRect(0, 0, 800, 600);
        sprite.graphics.endFill();
      addChild(sprite);
      
      var balloon:Sprite = new rBalloon;
      balloon.x = 500;
      balloon.y = 180;
      // addChild(balloon);
      
      radioEn = new RadioButton(this, 50,  5, "en", false, onLanguageChange);
      radioEs = new RadioButton(this, 100, 5, "es",  true, onLanguageChange);
      
      textEdit = new TextEdit();      
        textEdit.x = 200;
        textEdit.y = 400;
        textEdit.addEventListener(TextEvent.TEXT_INPUT, onTagCodeChange, true);
        textEdit.addEventListener(KeyboardEvent.KEY_UP, onTagCodeChange, true);
      addChild(textEdit);
      
      loc = new Localization(null, "es");
      
      recreateList();
      
      /////////////////////////////////////////////////////////////////////////
      /// Add list and add/delete elements buttons.
      /////////////////////////////////////////////////////////////////////////
      tagText = new Text(this, 0, list.y + list.height, "NEW_TAG");
      tagText.width = 150;
      tagText.height = 20;
      tagText.textField.multiline = false;
      tagText.textField.restrict = "A-Z_0-9";
      tagText.addEventListener(KeyboardEvent.KEY_DOWN, onTagTextKeyDown);
      
      var addBtn:PushButton = new PushButton(this, tagText.width, list.y + list.height, "+", onAddBtn);
      addBtn.width = 25;
      var deleteBtn:PushButton = new PushButton(this, addBtn.x + addBtn.width, list.y + list.height, "-", onDeleteBtn);
      deleteBtn.width = 25;
      
      new PushButton(this, 0, 580, "LOAD", onLoad);
      new PushButton(this, 100, 580, "SAVE", onSave);
      
      moodCombo = new ComboBox(this, 700, 380, Localization.MOODS[0], Localization.MOODS);
      moodCombo.selectedIndex = 0;
      new Label(this, moodCombo.x - 35, moodCombo.y, "Mood");
      
      var animateBtn:PushButton = new PushButton(this, 220, 380, "Animate Text", onAnimate);
      animateBtn.width = 80;
      
      var viewAsModal:PushButton = new PushButton(this, animateBtn.x + animateBtn.width, 380, "View as Modal", onModal);
      viewAsModal.width = 80;
            
      // Adds the first tag to work with.
      onAddBtn();
    }
    
    private function onAnimate(e:Event):void
    {
      if (!validSelection()) return;
      
      var tt:TextTyped = new TextTyped(preview);
      tt.type(loc.translate(loc.tags[list.selectedIndex]));
    }    
    
    private function onLoad(e:Event):void
    {
      loc.load(_loaded);
    }
    
    private function _loaded(e:Event):void
    {
      recreateList();
    }
    
    private function onSave(e:Event):void
    {
      loc.export();
    }
    
    private function onDeleteBtn(e:Event):void
    {
      if (!validSelection())
      {
        new ModalDialog(this, "There's no tag selected in the list.", style);
        return;
      }
      
      if (list.items.length <= 1)
      {
        new ModalDialog(this, "You can't delete the last tag.", style);
        return;
      }
      
      new ModalDialog(this, 'Tag "' + loc.tags[list.selectedIndex] + '" will be deleted.\nContinue?', style, "Yes", deleteDialog, "Cancel");
    }
    
    private function deleteDialog(result:int):void
    {
      if (result != ModalDialog.RESULT_YES) return;
      
      var idx:int = list.selectedIndex;
      var tag:String = loc.tags[idx];
      loc.removeTag(tag);
      
      recreateList();
      
      list.selectedIndex = Math.max(0, idx - 1);
      
      if (validSelection())
      {
        refreshPreview();
        refreshTagCode();
      }
    }
    
    private function onTagTextKeyDown(e:KeyboardEvent):void
    {
      if (e.keyCode == Keyboard.ENTER)
      {
        onAddBtn(e);
      }
    }
    
    private function onAddBtn(e:Event = null):void
    {
      if (tagText.text == "")
      {
        new ModalDialog(this, "You must write a name for the tag first", style);
        return;
      }
      
      for (var i:int = 0; i < loc.tags.length; i++)
      {
        if (loc.tags[i] == tagText.text)
        {
          new ModalDialog(this, 'Tag "' + tagText.text + '" already exists', style);
          return;
        }
      }
      
      loc.addTag(tagText.text);
      recreateList();
      list.selectedIndex = list.items.length - 1;
      onListClick(e);
      
      if (validSelection())
      {
        refreshPreview();
        refreshTagCode();
      }
    }
    
    private function recreateList():void
    {
      if (list)
      {
        list.removeEventListener(MouseEvent.CLICK, onListClick);
        removeChild(list);
      }
        
      var array:Array = new Array();
      for (var i:int = 0; i < loc.tags.length; i++)
        array.push(loc.tags[i]);
      
      list = new List(this, 0, 20, array);
      list.height = 540;
      list.width = 200;
      list.addEventListener(MouseEvent.CLICK, onListClick);
    }
    
    private function onListClick(e:Event):void
    {
      if (!validSelection())
        list.selectedIndex = list.items.length - 1;

      loc.dic[loc.tags[previousSelected]].mood = moodCombo.selectedItem;
      refreshTagCode();
      refreshPreview();
      tagText.text = loc.tags[list.selectedIndex];
      
      previousSelected = list.selectedIndex;
    }
    
    private function onTagCodeChange(e:Event):void
    {
      if (!validSelection()) return;
      
      // Updates lockit and preview
      loc.dic[loc.tags[list.selectedIndex]].text[loc.language] = textEdit.text;
      refreshPreview();
    }
    
    private function validSelection():Boolean
    {
      return list.selectedIndex >= 0 && list.selectedIndex < loc.tags.length;
    }
    
    private function refreshTagCode():void
    {
      var trans:String = loc.tags[list.selectedIndex];
      textEdit.text = loc.translate(trans);
      moodCombo.selectedItem = loc.translateEx(trans).mood;
    }
    
    private function refreshPreview():void
    {
      // Preview textfield
      if (preview) removeChild(preview);
      
      preview = new TextField();
      preview.x = 230;
      preview.y = 100;
      preview.multiline = true;
      // preview.autoSize = TextFieldAutoSize.LEFT;
      preview.wordWrap = true;
      preview.width = 500;
      preview.height = 200;
      addChild(preview);
      // style.parseCSS(new rStyle);
      preview.styleSheet = style;
      preview.background = true;      
      
      var trans:String = loc.tags[list.selectedIndex];
      preview.htmlText = loc.translate(trans);
    }
    
    private function onModal(e:Event):void
    {
      if (validSelection())
        new ModalDialog(this, loc.translate(loc.tags[list.selectedIndex]), style, "Close");
    }
    
    private function onLanguageChange(e:Event):void
    {
      loc.language = (e.target as RadioButton).label;
      
      if (validSelection())
      {
        refreshPreview();
        refreshTagCode();
      }
    }
    
    // private var tagCode:TextField;
    private var textEdit:TextEdit;
    private var preview:TextField;
    private var list:List;
    private var style:StyleSheet = new StyleSheet();
    
    private var radioEn:RadioButton;
    private var radioEs:RadioButton;
    
    private var tagText:Text;
    
    private var moodCombo:ComboBox;
    
    private var previousSelected:int = 0;
	}
	
}